package com.gmail.flashpig8014.pig;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gmail.flashpig8014.pig.util.StringUtils;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;

@SuppressWarnings("serial")
public class PigServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("UTF-8");
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();
		Query q = new Query("Record");
		q.addSort("score", SortDirection.DESCENDING);
		q.addSort("bugCount", SortDirection.DESCENDING);
		q.addSort("updateTime", SortDirection.ASCENDING);
		q.addSort("nick", SortDirection.ASCENDING);
		PreparedQuery pq = datastore.prepare(q);

		for (Entity result : pq.asIterable()) {
			String nick = (String) result.getProperty("nick");
			long bugCount = (Long) result.getProperty("bugCount");
			long score = (Long) result.getProperty("score");
			resp.getWriter().println(nick + "," + bugCount + "," + score);
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String record = req.getParameter("record");
		if (record == null || record.length() == 0) {
			return;
		}
		String[] fields = record.split(";");
		if (fields.length != 3) {
			return;
		}
		String nick = fields[0].trim();
		int bugCount = StringUtils.parseInt(fields[1]);
		int score = StringUtils.parseInt(fields[2]);
		if (nick.length() == 0 || bugCount == 0 || score == 0) {
			return;
		}
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();

		Entity r = new Entity("Record");
		r.setProperty("nick", nick);
		r.setProperty("bugCount", bugCount);
		r.setProperty("score", score);
		r.setProperty("updateTime", System.currentTimeMillis());
		datastore.put(r);

		resp.setContentType("text/plain");
		resp.setCharacterEncoding("UTF-8");
		resp.getWriter().println("upload success");
	}

}
